<script setup lang="tsx">
import { computed, reactive, ref, watch } from 'vue';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict';
import type { Notice, NoticeEditAndCreateParams, User } from '@/service/api';
import { createNotice, updateNotice } from '@/service/api';
import WangEditor from '@/components/custom/wange-editor/index.vue';
import { useBoolean } from '~/packages/hooks/src';
import EmployeePickModal from '../../user/modules/employee-pick.vue';

defineOptions({
  name: 'NoticeOperateModal'
});

export type OperateType = NaiveUI.TableOperateType;

interface Props {
  /** the type of operation */
  operateType: OperateType;
  /** the edit menu data or the parent menu data when adding a child menu */
  rowData?: Notice | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { bool: appointUserVisible, setTrue: openAppointUserModal } = useBoolean();

const { formRef, validate, restoreValidation } = useNaiveForm();
const { defaultRequiredRule } = useFormRules();
const submitLoading = ref(false);

const title = computed(() => {
  const titles: Record<OperateType, string> = {
    add: $t('page.manage.notice.add'),
    edit: $t('page.manage.notice.edit')
  };
  return titles[props.operateType];
});

type Model = Pick<
  NoticeEditAndCreateParams,
  'title' | 'content' | 'type' | 'level' | 'targetType' | 'targetUserIds'
> & {
  id: number | null;
};

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
    id: null,
    type: null,
    title: '',
    content: '',
    level: null,
    targetType: 1,
    targetUserIds: []
  };
}

type RuleKey = Extract<keyof Model, 'type' | 'title' | 'content'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  type: defaultRequiredRule,
  title: defaultRequiredRule,
  content: defaultRequiredRule
};

const employeeList = ref<User[]>([]);

const targetTypeRadio = [
  {
    value: 1,
    label: $t('page.manage.notice.targetTypeAll')
  },
  {
    value: 2,
    label: $t('page.manage.notice.targetTypeUser')
  }
];

function closeDrawer() {
  submitLoading.value = false;
  visible.value = false;
}

async function handleSubmit() {
  await validate();

  submitLoading.value = true;
  if (props.operateType === 'edit') {
    // request
    const { error } = await updateNotice(model.id as number, model);

    if (!error) {
      window.$message?.success($t('common.updateSuccess'));
      closeDrawer();
      emit('submitted');
    }
  } else {
    const { error } = await createNotice(model);
    if (!error) {
      window.$message?.success($t('common.addSuccess'));
      closeDrawer();
      emit('submitted');
    }
  }
}

async function handleInitModel() {
  Object.assign(model, createDefaultModel());

  if (!props.rowData) return;

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model, props.rowData);
  }
}

function handleAppointUser() {
  openAppointUserModal();
}

function submittedAppointUser(employeeSelectedList: User[] = []) {
  model.targetUserIds = employeeSelectedList.map(item => item.id);
  employeeList.value = employeeSelectedList;
}

const handleEmployeeSelectedDelete = (tag: User) => {
  if (model.targetUserIds) {
    model.targetUserIds = model.targetUserIds.filter(item => !(tag.id.toString() === item.toString()));
  }

  employeeList.value = employeeList.value.filter(item => !(tag.id.toString() === item.id.toString()));
};

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
    employeeList.value = [];
  }
});
</script>

<template>
  <div>
    <NModal v-model:show="visible" :title="title" preset="card" :mask-closable="false" class="w-300">
      <NScrollbar class="max-h-250 pr-20px">
        <NForm ref="formRef" :model="model" :rules="rules" label-placement="left" label-width="auto">
          <NFormItem :label="$t('page.manage.notice.noticeTitle')" path="title">
            <NInput v-model:value="model.title" :placeholder="$t('page.manage.notice.form.noticeTitle')" />
          </NFormItem>
          <NFormItem :label="$t('page.manage.notice.content')" path="content">
            <WangEditor
              v-model="model.content as string"
              class="max-h-150 min-h-120 border-1 border-gray-500/20 rounded-md"
            />
          </NFormItem>
          <NFormItem :label="$t('page.manage.notice.type')" path="type" class="w-50%">
            <NSelect
              v-model:value="model.type"
              :options="getIntDictOptions(DICT_TYPE.SYSTEM_NOTICE_TYPE)"
              clearable
              :placeholder="$t('page.manage.notice.form.type')"
            />
          </NFormItem>
          <NFormItem :label="$t('page.manage.notice.level')" path="level" class="w-50%">
            <NSelect
              v-model:value="model.level"
              :options="getStrDictOptions(DICT_TYPE.SYSTEM_NOTICE_LEVEL)"
              clearable
              :placeholder="$t('page.manage.notice.form.level')"
            />
          </NFormItem>
          <NFormItem :label="$t('page.manage.notice.targetType')" path="targetType">
            <NRadioGroup v-model:value="model.targetType" name="targetType">
              <NSpace>
                <NRadio v-for="target in targetTypeRadio" :key="target.value" :value="target.value">
                  {{ target.label }}
                </NRadio>
              </NSpace>
            </NRadioGroup>
          </NFormItem>
          <NFormItem v-if="model.targetType == 2" :label="$t('page.manage.notice.appointUser')" path="targetUserIds">
            <NButton size="small" ghost type="primary" @click="handleAppointUser">
              <template #icon>
                <icon-ant-design:solution-outlined class="text-icon" />
              </template>
              {{ $t('page.manage.notice.appointUser') }}
            </NButton>
          </NFormItem>
        </NForm>
        <div>
          <NTag
            v-for="tag in employeeList"
            :key="tag.id"
            class="mr-1"
            size="small"
            closable
            type="primary"
            @close="handleEmployeeSelectedDelete(tag)"
          >
            <span class="ml-5 truncate text-center">{{ tag.nickname }}</span>
          </NTag>
        </div>
      </NScrollbar>
      <template #footer>
        <NSpace justify="end" :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" :loading="submitLoading" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NModal>
    <EmployeePickModal
      v-model:visible="appointUserVisible"
      :single-selection="2"
      :employee-list="employeeList"
      @fill="submittedAppointUser"
    />
  </div>
</template>

<style scoped>
.flex-end {
  display: flex;
  justify-content: flex-end;
}
</style>
